package com.common.sdk.net.connect.http.interceptor;

import com.android.sohu.sdk.common.toolbox.StringUtils;
import com.common.sdk.net.connect.http.util.OkhttpCacheUtil;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by chengjiangsang116630 on 2018/1/30.
 * 用于应用拦截器
 */

public class SohuCacheInterceptor extends ExceptionCatchedInterceptor {

    @Override
    protected Response realIntercept(Chain chain) throws IOException {
        Request request = chain.request();
        String cacheControl = request.header(CacheConstants.CACHE_CONTROL);
        if (cacheControl != null && cacheControl.contains(CacheConstants.MAX_AGE)) {
            String strMaxAge = cacheControl.substring(cacheControl.indexOf(CacheConstants.MAX_AGE) + 8);
            long maxAge = Long.parseLong(strMaxAge);
            // 在外部未设置的情况下再根据request得到相应的过期时间,优先以外部设置的为准
            boolean isExpireTimeSet = OkhttpCacheUtil.isExpiredTimeSet(maxAge);
            if (!isExpireTimeSet) {
                // 得到request相应的过期时间
                int expireTime = OkhttpCacheUtil.getExpiredTime(request);
                if (expireTime != maxAge) {
                    request = request.newBuilder().header(CacheConstants.CACHE_CONTROL, String.valueOf(expireTime)).build();
                }
            }
        }
        Response response = chain.proceed(request);
        return response;
    }

}
